import logging
import json
import yaml
import requests
import pandas as pd

from auto.apiSecurity.common.addMockOpen import add_mock_open
from auto.apiSecurity.common.addTestConfig import add_test_config
from auto.apiSecurity.common.publishApi import publish_api


def add_api_none(env, csv_file):
    global api_version_id, requestPath, requestMethod, openPath
    with open('data/config/token.yml', 'r') as f:
        config = yaml.safe_load(f)
    with open('data/config/config.yaml', 'r') as f2:
        config_data = yaml.safe_load(f2)
    with open('data/config/project_id.txt', 'r') as f3:
        project_id = f3.read().strip()
    with open('data/config/directory_id.txt', 'r') as f4:
        directory_id = f4.read().strip()

    url = config_data['environments'][env]['host'] + config_data['environments'][env]['add_api']
    token = config['token']
    protocol = config_data['environments'][env]['protocol']
    headers = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token, 'Tenantid': project_id}
    query_params = {
    }

    # 加载 CSV 文件
    df = pd.read_csv(csv_file)

    for index, row in df.iterrows():
        apiName = row['apiName']  # 从 CSV 读取 apiName
        protocol = row['protocol']  # 从 CSV 读取 protocol
        pushPortal = row['pushPortal']  # 从 CSV 读取 pushPortal
        requestMethod = row['requestMethod']  # 从 CSV 读取 requestMethod
        requestPath = row['requestPath']  # 从 CSV 读取 requestPath
        openPath = row['openPath']  # 从 CSV 读取 openPath
        mockConfig = row['mockConfig']  # 从 CSV 读取 mockConfig
        mockOpen = row['mockOpen']  # 从 CSV 读取 mockOpen 是否开启Mock
        detail = row['detail']  # 从 CSV 读取 detail API测试配置
        test = row['test']  # 从 CSV 读取 test 是否保存Test

        payload = {
            "baseApiVersion": {
                "baseApiVersionExtra": {
                    "responseContentType": "JSON",
                    "requestContentType": "JSON",
                    "requestData": "",
                    "responseData": ""
                },
                "baseApiVersionParams": [],
                "versionDesc": "",
                "sort": 0
            },
            "project": project_id,
            "apiName": apiName,
            "protocol": protocol,
            "pushPortal": pushPortal,
            "requestMethod": requestMethod,
            "requestPath": requestPath,
            "directory": directory_id,
            "createType": "transparent_http",
            "openStandardType": "none",
            "needAuth": False
        }
        data = json.dumps(payload)
        # print(data)
        try:
            # 发送 POST 请求
            response = requests.post(url, data=data, headers=headers, params=query_params)
            # 检查响应状态
            response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
            parsed_data = response.json()
            # 提取 api_version_id
            api_version_id = parsed_data['data']['apiVersionId']
            # 提取 api_version_id
            api_id = parsed_data['data']['id']
            if api_version_id:
                # print(f"提取到的 api_version_id: {api_version_id}")

                # 保存 api_version_id 到文件
                with open('data/config/api_version_id.txt', 'w') as id_file:
                    id_file.write(api_version_id)
                logging.info("成功----已提取到API版本ID: %s", api_version_id)
            else:
                logging.warning("失败----未能在响应中找到 api_version_id")
            if api_id:
                # print(f"提取到的 api_id: {api_id}")

                # 保存 api_id 到文件
                with open('data/config/api_id.txt', 'w') as id_file:
                    id_file.write(api_id)
                logging.info("成功----已提取到APIID: %s", api_id)
            else:
                logging.warning("失败----未能在响应中找到 api_id")

        except requests.exceptions.RequestException as e:
            logging.error("请求失败: %s", str(e))
        except json.JSONDecodeError:
            logging.error("解析 JSON 响应失败")
        publish_api(env, api_version_id, requestPath, requestMethod, openPath)
        add_mock_open(env, api_version_id, mockConfig, mockOpen, apiName)
        add_test_config(env, api_version_id, detail, test, openPath)
